package com.cy.pj.goods;

import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao {
    @Autowired
    private DataSource dataSource;

    public List<Map<String, Object>> findGoods() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from tb_goods");
            List<Map<String, Object>> goodsList = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> rowMap = goodMap(resultSet);
                /*rowMap.put("id", resultSet.getInt("id"));
                rowMap.put("name", resultSet.getString("name"));
                rowMap.put("remark", resultSet.getString("remark"));
                rowMap.put("createdTime", resultSet.getTimestamp("createdTime"));*/
                goodsList.add(rowMap);
            }
            return goodsList;

        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);//转换为非检查异常（编译时不检测的异常）,这个是抛出异常，就不需要在catch中进行一个return
        } finally {
            if (resultSet != null) try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (statement != null) try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (connection != null) try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public Map<String, Object> goodMap(ResultSet resultSet) throws SQLException {
        Map<String, Object> goodsMap = new HashMap<>();
        int rowcout = resultSet.getMetaData().getColumnCount();
        for (int i = 0; i < rowcout; i++) {
            goodsMap.put(resultSet.getMetaData().getColumnLabel(i + 1), resultSet.getObject(resultSet.getMetaData().getColumnLabel(i + 1)));
        }
        return goodsMap;
    }

}
